/**
 * 角色关联用户——选择用户窗口
 * @author linzongxue
 */
define(function(){
	var SelectUserWindow = Ext.extend(Ext.Window, {
		roleId: null, //角色ID
		selectedUserIds: null, //已关联的用户ID
		title: '角色关联用户——选择用户',
		width: 700,
		resizable: false,
		modal: true,
	    animateTarget: cu.getDefaultAnimateTarget(),
        bodyStyle: 'padding:1px;',
		iconCls: 'icon-window',
		initComponent: function(){
			Ext.apply(this, {
				tbar: this.createTbar(),
				items: [
				    this.userGrid = this.createUserGridPanel()
				],
				buttons: [
					{text: '确定', width:60, handler: this.ok, iconCls: 'icon-ok', scope: this},
					{text: '关闭', width:60, handler: this.close, iconCls: 'icon-close', scope: this}
				],
				listeners:{
					afterrender: this.refresh
				}
			});
			SelectUserWindow.superclass.initComponent.call(this);
		},
		ok: function(){
			var rows = this.userGrid.getSelectionModel().getSelections();
			if (lu.isEmpty(rows)){
				cu.hint('请选择要关联的用户');
				return;
			}
			cu.post({
				url: 'sys/role/addUsersToRole.do',
				params: {roleId: this.roleId, userIds: lu.pluck(rows, 'id')},
				success: function(data){
					this.close();
					this.callback.call(this.cbScope, rows.length);
				},
				scope: this
			});
		},
		queryUsers: function(){
			var store = this.userGrid.store;
			this.getTopToolbar().cascade(function(c){
				if (!c.name || !c.getValue) return;
				c.getValue() ? store.baseParams[c.name] = c.getValue() : delete store.baseParams[c.name];
			});
			store.load();
		},
		refresh: function(){
			this.getTopToolbar().cascade(function(c){
				if(c.name) c.setValue(null);
			});
			this.queryUsers();
		},
		createUserGridPanel: function(){
			var store = new Ext.data.JsonStore({
			    remoteSort: true, 
			    root: 'result', totalProperty: 'totalItems', idProperty: 'id',
			    fields: ['loginName', 'name', 'position', 'departName', 'gender', 'isAdmin'],
			    url: 'sys/user/query.do'
			});
			var sm = new Ext.grid.CheckboxSelectionModel({
		    	 listeners:{
		             beforerowselect: function(selModel, rowIndex, keepExisting, record) {
		            	 //不允许选择已经关联的用户(disabled属性值在GridView的refresh事件中设置)
		                 return !record.disabled;
		             }
		         }
		    });
			var grid = new Ext.grid.GridPanel({
				height: cu.getWinHeight(500) - 100,
				border: false,
				stripeRows: true,
			    enableHdMenu: false,
			    loadMask: {msg: '正在加载数据...'},
				store: store,
				sm: sm,
				columns: [
					new Ext.grid.RowNumberer(),
				    sm,
					{header: '账号', width: 120, dataIndex: 'loginName'},
					{header: '姓名', width: 100, dataIndex: 'name'},
					{header: '机构', width: 150, dataIndex: 'departName'},
					{header: '性别', width: 50, dataIndex: 'gender', renderer: this.renderGender},
					{header: '岗位', width: 120, dataIndex: 'position'}
				],
				bbar: cu.createPagingBar(store)
			});
			//处理已选择过的用户ID，改变该行的字体颜色，去掉checkbox
			grid.getView().on('refresh', function(view){
				if (Ext.isEmpty(this.selectedUserIds)) return;
				Ext.each(store.getRange(), function(r, i){
					if (this.selectedUserIds.indexOf(r.id) > -1){
						r.disabled = true; //标记为不可选
						view.getCell(i, 1).innerHTML = '';
						Ext.get(view.getRow(i)).setStyle('color', '#aaa');
					}
				}, this);
			}, this);
			
			return grid;
		},
		createTbar: function(){
			return new Ext.Toolbar({
				items: [
			        {text: '查找：', xtype: 'label', style:'font-weight:bold;margin:2px 5px;'},
				    {text: '所属机构：', xtype: 'label'},
				    {
						xtype:'combotree',
						name: 'departId',
						width: 120,
						listWidth: 200,
						dataUrl: 'sys/depart/getDepartTreeData.do?',
						nodePathUrl: 'sys/util/getEntityAttrPath.do?c=sys.entity.Department',
						root: {id:'root', text:'/', expanded: true},
						rootVisible: true,
						rootSelectable: true,
						rootValue: null
			        },
				    {text: '账号：', xtype: 'label', style:'margin-left:5px;'},
				    {xtype: 'textfield', name: 'loginName', width: 70},
				    {text: '姓名：', xtype: 'label', style:'margin-left:5px;'},
				    {xtype: 'textfield', name: 'name', width: 70},
			        {handler: this.queryUsers, scope: this, iconCls:'icon-find', tooltip:'查找用户'},
			        {handler: this.refresh, scope: this, iconCls:'icon-refresh', tooltip:'清空查询条件并刷新'}
				],
				listeners: {
					afterrender: function(){
						//绑定回车事件
						this.cascade(function(c){
							if (!c.name) return;
							c.on('specialKey', function(field, e){ //回车搜索
		                		if (e.getKey() == e.ENTER) this.ownerCt.queryUsers();
		                	}, this);
						}, this);
					}
				}
			});
		},
		renderGender: function(value){
			return value ? au.getDictText('gender', value) : '';
		}
	});
	return SelectUserWindow;
});